package cn.jbit.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.jbit.cache.MemCache;
import cn.jbit.pojo.Student;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.*;

@Controller
@RequestMapping("/student")
public class StudentController {
	
	
	@RequestMapping("/list")
	public String stuList(HashMap<String,Object> mp){
		/*1、如何从Controller将数据传递给所对应View呢？
		 * 1)、Model
		 * 2)、ModelMap
		 * 3)、Map
		 * 4)、ModelAndView
		 * */
		List<Student> stuList = MemCache.findAll();
		mp.put("stuList", stuList);
		return "studentView";
	}
	
	@RequestMapping("/list2")
	public ModelAndView stuView(){
		List<Student> stuList = MemCache.findAll();
		ModelAndView mv = new ModelAndView();
		mv.setViewName("studentView");//设置逻辑视图名
		mv.addObject("stuList", stuList);
		return mv;
	}
	
	/*2、如何将View中的数据传递所对应Controller呢？
	 * 1)、基本数据类型映射(int、double、String等)
	 * 2)、简单对象类型映射(JavaBean)
	 * */
	//初始化添加学员信息的页面
	@RequestMapping(value="/add",method={RequestMethod.GET})
	public String addStudent(){
		
		return "studentAdd"; //转发-逻辑视图名
	}
	
	//保存学员信息
	@RequestMapping(value="/add",method={RequestMethod.POST})
	public String addStudent(Student stu,Model model){
		boolean result = MemCache.addStudent(stu);
		if(result){
			return "redirect:/student/list"; //重定向 是 访问url，而不是逻辑视图名
		}
		else{
			model.addAttribute("errmsg", "添加学员信息失败，学号必须唯一!");
			return "studentAdd"; //转发-逻辑视图名
		}
		
	}
	
	@RequestMapping(value="/update",method={RequestMethod.GET})
	public String updateStudent(Integer id,Model model){
		Student stu = MemCache.findById(id);
		System.out.println(stu);
		model.addAttribute("stu", stu);
		return "studentUpdate";
	}
	
	
	@RequestMapping(value="/update",method={RequestMethod.POST})
	public String updateStudent(Student stu,Model model){
		boolean result = MemCache.updateStudent(stu);
		if(result){
			return "redirect:/student/list"; //重定向 url
		}
		else
		{
			model.addAttribute("errmsg", "修改学员信息失败！");
			return "studentUpdate";
		}
	}
	
	
	@RequestMapping(value="/delete",method={RequestMethod.GET})
	public String deleteStudent(Integer id,HttpServletResponse response){
		MemCache.deleteStudent(id);
		return "redirect:/student/list"; //重定向 url
		
	}
	
}
